

class  chat {
	constructor(arg) {
	    this.url = arg.url
		this.isOnline = false
		this.socket = null
		this.reconnectTime = 0
		this.isOpenReconnect = true
		
		this.token  = uni.getStorageSync('token')
		if (this.token)  {
			// 连接和监听
			this.connectSocket()
		}
	}
	// 断线重连
	reconnect() {
		if(this.isOnline){
			return
		}
		if(this.reconnectTime >= 3){
			return this.reconnectConfirm()
		}
		this.reconnectTime += 1
		this.connectSocket()
	}
	// 连接socket
	connectSocket() {
		this.socket = uni.connectSocket({
			url: this.url,
			complete: () => {}
		})
		// 监听连接成功
		this.socket.onOpen(() => this.onOpen())
		// 监听接收信息
		this.socket.onMessage((res)=>this.onMessage(res))
		// 监听断开
		this.socket.onClose(()=>this.onClose())
		// 监听错误
		this.socket.onError(()=>this.onError())
	}
	// 监听打开
	onOpen() {
		// 在线
		this.isOnline = true
		console.log('socket连接成功')
		this.isOpenReconnect = true
	}
	// 监听关闭
	onClose() {
		// 下线
		this.isOnline = false
		this.socket = null
		if(this.isOpenReconnect){
			this.reconnect()
		}
		console.log('socket连接关闭')
	}
	// 监听连接错误
	onError(){
		// 用户下线
		this.isOnline = false
		this.socket = null
		console.log('socket连接错误')
	}
	// 监听接收消息
	onMessage(data) {
		let res = JSON.parse(data.data)
		console.log('监听接收消息',res)
	}
	// 断线重连提示
	reconnectConfirm() {
		this.reconnectTime = 0
		this.connectSocket()
	}
	// 验证是否上线
	checkOnline(){
		if(!this.isOnline){
			// 断线重连提示
			this.reconnectConfirm()
			return false
		}
		return true
	}
}